import request from '@/utils/request'
import CryptoJS from 'crypto-js'

// 计算签名
function computeSignature(accessKeySecret, canonicalString) {
  return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(canonicalString, accessKeySecret))
}

// 获取OSS临时访问凭证
const getOssKey = async () => {
  try {
    const res = await request({
      url: '/wx/uploadKey',
      method: 'get'
    })

    const date = new Date()
    date.setHours(date.getHours() + 1)
    const policyText = {
      expiration: date.toISOString(), // 设置policy过期时间
      conditions: [
        // 限制上传大小
        ["content-length-range", 0, 1024 * 1024 * 1024],
      ],
    }

    const policy = btoa(JSON.stringify(policyText)) // policy必须为base64的string
    const signature = computeSignature(res.data.access_key_secret, policy)
    const formData = {
      OSSAccessKeyId: res.data.access_key_id,
      signature,
      policy,
      'x-oss-security-token': res.data.security_token
    }
    return formData
  } catch (error) {
    console.error('获取OSS密钥失败:', error)
    throw error
  }
}

// 获取用户ID
const getUserId = () => {
  try {
    // 从localStorage获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    console.log(userInfo,"userInfo");

    return userInfo?.id || userInfo?.userId || 'anonymous'
  } catch (error) {
    console.error('获取用户ID失败:', error)
    return 'anonymous'
  }
}

// 获取上传路径前缀
const getUploadPathPrefix = () => {
  return 'RuranDev'
  // return process.env.NODE_ENV === 'production' ? 'RuranProd' : 'RuranDev'
}

// 使用STS临时凭证上传文件到OSS
export const uploadToOssWithSTS = async (file) => {
  try {
    const credentials = await getOssKey()
    const host = 'https://oss.ptyxlm.cn/'
    const signature = credentials.signature
    const OSSAccessKeyId = credentials.OSSAccessKeyId
    const policy = credentials.policy
    const key = getUploadPathPrefix() + '/temporary/' + `${getUserId()}/${file.name ? file.name.split('.')[0] + '_' : ''}` + Date.now() + "." + file.name.split('.').pop()
    const securityToken = credentials['x-oss-security-token']
console.log(key);

    const formData = new FormData()
    formData.append('key', key)
    formData.append('policy', policy)
    formData.append('OSSAccessKeyId', OSSAccessKeyId)
    formData.append('signature', signature)
    formData.append('x-oss-security-token', securityToken)
    formData.append('file', file)

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()

      xhr.open('POST', host, true)

      xhr.onload = function() {
        if (xhr.status === 204) {
          resolve('https://oss.ptyxlm.cn/' + key)
        } else {
          reject(new Error('上传失败'))
        }
      }

      xhr.onerror = function() {
        reject(new Error('上传失败'))
      }

      xhr.send(formData)
    })
  } catch (error) {
    console.error('uploadToOssWithSTS error:', error)
    throw error
  }
}
